//
//  TG_Global.m
//  TongGuanLease
//
//  Created by 张奇 on 2022/4/14.
//

#import "TG_Global.h"
#import "LBXPermissionSetting.h"
#import "LBXPermission.h"
#import "ZFImagePicker.h"
#import "MBProgressHUD+RY.h"
#import "EventStatisticsAPIRequest.h"

@implementation TG_Global

+ (instancetype)sharedInstance
{
    static TG_Global *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[TG_Global alloc] init];
    });
    return instance;
}

///拍照或从相机选取单张照片
- (void)selectSingleImageWithUploadImageType:(UploadImageType)uploadImageType
                                    selectVC:(UIViewController *)presentVC
                                     canEdit:(BOOL)canEdit
                                     success:(void(^)(UIImage * image, TGUrlInfoModel *urlInfoModel))success {
    
    NSArray *filPathArray = @[@"USER_SERVICE", @"EQUIPMENT_SERVICE", @"SETTLEMENT_SERVICE", @"CRM_SERVICE", @"CONTRACT_SERVICE", @"ASSETS_SERVICE", @"SYSTEM_SERVICE", @"WORK_ORDER_SERVICE", @"NCC_AGGREGATION_SERVICE", @"WORKFLOW_SERVICE", @"THIRD_PARTY_SERVICE", @"RULE_ENGINE_SERVICE", @"SCHEDULE_SERVICE", @"ANALYSIS_SERVICE"];
    
    [LEEAlert actionsheet].config
        .LeeActionSheetBottomMargin(0)
        .LeeStatusBarStyle(UIStatusBarStyleLightContent)
    .LeeAddAction(^(LEEAction * _Nonnull action) {
        action.title = @"拍照上传";
        action.titleColor = RGBA(51, 51, 51, 1);
        action.font = TGAutoFont(18);
        action.clickBlock = ^{
            [self getImgAndUploadWithIsTakePhoto:YES filePath:filPathArray[uploadImageType] canEdit:canEdit complemtntion:^(UIImage *image, TGUrlInfoModel *urlInfoModel) {
                if (success) {
                    success(image, urlInfoModel);
                }
            }];
        };
    }).LeeAddAction(^(LEEAction * _Nonnull action) {
        action.title = @"本地上传";
        action.titleColor = RGBA(51, 51, 51, 1);
        action.font = TGAutoFont(18);
        action.clickBlock = ^{
            [self getImgAndUploadWithIsTakePhoto:NO filePath:filPathArray[uploadImageType] canEdit:canEdit complemtntion:^(UIImage *image, TGUrlInfoModel *urlInfoModel) {
                if (success) {
                    success(image, urlInfoModel);
                }
            }];
        };
    }).LeeAddAction(^(LEEAction * _Nonnull action) {
        action.title = @"取消";
        action.type = LEEActionTypeCancel;
        action.titleColor = RedColor;
        action.font = TGAutoFont(18);
        action.clickBlock = ^{
        };
    }).
    LeeConfigMaxWidth(^CGFloat(LEEScreenOrientationType type, CGSize size)  {
        return CGRectGetWidth([[UIScreen mainScreen] bounds]);
    }).LeeShow();

}

- (void)getImgAndUploadWithIsTakePhoto:(BOOL)isTakePhoto filePath:(NSString *)filePath canEdit:(BOOL)canEdit
                         complemtntion:(void(^)(UIImage *image, TGUrlInfoModel *urlInfoModel))complemtntion {
    ZFImagePicker *picker = [[ZFImagePicker alloc] init];
    picker.isEdit = canEdit;
    if (isTakePhoto) {
        picker.sType = SourceTypeCamera;
    } else {
        picker.sType = SourceTypeLibrary;
    }
    picker.pickImage = ^(UIImage *image,NSString *type,NSString *name){
        NSLog(@"image:%@ \n type:%@ \n name:%@",image,type,name);
        
        [TGNetworkManager uploadImage:image filePath:filePath success:^(TGResponseItem *responseItem) {
            if (responseItem.success) {
                TGUrlInfoModel *urlInfoModel = [TGUrlInfoModel modelWithJSON:responseItem.data];
                if (complemtntion) {
                    complemtntion(image, urlInfoModel);
                }
            }
        } failure:^(NSError *error) {
            
        }];
        
    };
    [self.getCurrentVC presentViewController:picker animated:YES completion:nil];
}


///身份证识别
- (void)diyCameraOrLibrarySelectVC:(UIViewController *)presentVC success:(void(^)(NSInteger type, UIImage * image))success {
    [LEEAlert actionsheet].config
    .LeeActionSheetBottomMargin(0)
    .LeeStatusBarStyle(UIStatusBarStyleLightContent)
    .LeeAddAction(^(LEEAction * _Nonnull action) {
        action.title = @"拍照上传";
        action.titleColor = RGBA(51, 51, 51, 1);
        action.font = TGAutoFont(18);
        action.clickBlock = ^{
            //调用自定义相机
            success(0,nil);
        };
    }).LeeAddAction(^(LEEAction * _Nonnull action) {
        action.title = @"本地上传";
        action.titleColor = RGBA(51, 51, 51, 1);
        action.font = TGAutoFont(18);
        action.clickBlock = ^{
            [self selectPhoto:NO selectVC:presentVC maxSelectCount:1 selectAssets:nil success:^(NSInteger type, UIImage *image, NSURL *videoUrl, NSArray<UIImage *> *images, NSArray<PHAsset *> *assets, BOOL isOriginal) {
                if (success) {
                    success(1, images.firstObject);
                }
            }];
        };
    }).LeeAddAction(^(LEEAction * _Nonnull action) {
        action.title = @"取消";
        action.type = LEEActionTypeCancel;
        action.titleColor = RedColor;
        action.font = TGAutoFont(18);
        action.clickBlock = ^{
        };
    }).
    LeeConfigMaxWidth(^CGFloat(LEEScreenOrientationType type, CGSize size)  {
        return CGRectGetWidth([[UIScreen mainScreen] bounds]);
    }).LeeShow();

}

- (void)cameraOrLibrarySelectVC:(UIViewController *)presentVC maxSelectCount:(NSInteger)count videoNumber:(NSInteger)videocount isAddWaterImage:(BOOL)isAddWaterImage selectAssets:(NSMutableArray<PHAsset *> *)selectAssets success:(void(^)(NSInteger type,UIImage *image, NSURL *videoUrl,NSArray<UIImage *> *  images, NSArray<PHAsset *> *  assets, BOOL isOriginal))success {
    
    if (isAddWaterImage) {
        [self selectPhoto:YES selectVC:presentVC maxSelectCount:count selectAssets:selectAssets success:success];
    } else {
        [LEEAlert actionsheet].config
        .LeeActionSheetBottomMargin(0)
        .LeeStatusBarStyle(UIStatusBarStyleLightContent)
        .LeeAddAction(^(LEEAction * _Nonnull action) {
            action.title = @"拍照上传";
            action.titleColor = RGBA(51, 51, 51, 1);
            action.font = TGAutoFont(18);
            action.clickBlock = ^{
                [self selectPhoto:YES selectVC:presentVC maxSelectCount:count selectAssets:selectAssets success:success];
            };
        }).LeeAddAction(^(LEEAction * _Nonnull action) {
            action.title = @"本地上传";
            action.titleColor = RGBA(51, 51, 51, 1);
            action.font = TGAutoFont(18);
            action.clickBlock = ^{
                [self selectPhoto:NO selectVC:presentVC maxSelectCount:count selectAssets:selectAssets success:success];
            };
        }).LeeAddAction(^(LEEAction * _Nonnull action) {
            action.title = @"取消";
            action.type = LEEActionTypeCancel;
            action.titleColor = RedColor;
            action.font = TGAutoFont(18);
            action.clickBlock = ^{
            };
        }).
        LeeConfigMaxWidth(^CGFloat(LEEScreenOrientationType type, CGSize size)  {
            return CGRectGetWidth([[UIScreen mainScreen] bounds]);
        }).LeeShow();
    }
}

- (void)cameraOrLibrarySelectVC:(UIViewController *)presentVC maxSelectCount:(NSInteger)count videoNumber:(NSInteger)videocount success:(void(^)(NSInteger type,UIImage *image, NSURL *videoUrl,NSArray<UIImage *> *  images, NSArray<PHAsset *> *  assets, BOOL isOriginal))success {
    [self cameraOrLibrarySelectVC:presentVC maxSelectCount:count videoNumber:videocount isAddWaterImage:NO selectAssets:nil success:success];
}

- (void)selectPhoto:(BOOL)isPhoto
           selectVC:(UIViewController *)presentVC
     maxSelectCount:(NSInteger)count
       selectAssets:(NSMutableArray<PHAsset *> *)selectAssets
            success:(void(^)(NSInteger type,UIImage *image, NSURL *videoUrl,NSArray<UIImage *> *  images, NSArray<PHAsset *> *assets, BOOL isOriginal))success {
    
        [LBXPermission authorizeWithType:LBXPermissionType_Camera completion:^(BOOL granted, BOOL firstTime) {
            if (granted) {
                
                
                if (isPhoto) {
                    // 直接调用相机
                    ZFImagePicker *picker = [[ZFImagePicker alloc] init];
                    picker.isEdit = NO;
                    if (isPhoto) {
                        picker.sType = SourceTypeCamera;
                    }else{
                        picker.sType = SourceTypeLibrary;
                    }
                    picker.pickImage = ^(UIImage *image,NSString *type,NSString *name){
                        NSLog(@"image:%@ \n type:%@ \n name:%@",image,type,name);
                        if (image && success) {
                            success(0,image,nil,nil,nil,NO);
                        }
                    };
                    [self.getCurrentVC presentViewController:picker animated:YES completion:nil];
                    
                } else {
                    ZLPhotoActionSheet *actionSheet = [[ZLPhotoActionSheet alloc] init];
                    actionSheet.sender = presentVC;
                    actionSheet.configuration.sessionPreset = ZLCaptureSessionPreset1920x1080;
                    actionSheet.configuration.showCaptureImageOnTakePhotoBtn = NO;
                    actionSheet.configuration.maxSelectCount = count;
                    actionSheet.configuration.allowSelectVideo = NO;
                    actionSheet.configuration.mutuallyExclusiveSelectInMix = YES;
                    actionSheet.configuration.allowSelectGif = NO;
                    actionSheet.configuration.statusBarStyle = UIStatusBarStyleDefault;
                    actionSheet.configuration.navTitleColor = RGB(44, 45, 46);
                    actionSheet.configuration.navBarColor = UIColorWhite;
                    
                    if (selectAssets) {
                        actionSheet.arrSelectedAssets = selectAssets;
                    }
                    actionSheet.cancleBlock = ^{
                        NSLog(@"取消选择图片");
                    };
                    [actionSheet setSelectImageBlock:^(NSArray<UIImage *> * _Nonnull images, NSArray<PHAsset *> * _Nonnull assets, BOOL isOriginal) {
                        NSLog(@"image:%@", images);
                        if (success) {
                            success(1,nil,nil,images,assets,isOriginal);
                        }
                    }];
                    [actionSheet  showPhotoLibraryWithSender:presentVC];
                    
                }
               
                
            }
            else if(!firstTime)
            {
                [LBXPermissionSetting showAlertToDislayPrivacySettingWithTitle:@"提示" msg:@"您好，需要使用相机来进行拍照、选择相册图片上传头像等功能，是否前往打开权限" cancel:@"暂不打开" setting:@"设置" ];
            }
            
        }];
     
}

- (ZLPhotoActionSheet *)photoActionSheet:(UIViewController *)sender
{
    ZLPhotoActionSheet *actionSheet = [[ZLPhotoActionSheet alloc] init];
    actionSheet.sender = sender;
    return actionSheet;
}

+(BOOL)callTip:(BOOL)showTip Phone:(NSString *)str {
    NSString *phone = str;
    if (phone != nil) {
        if (showTip) {
            [TGLEEAlert alertTitle:@"服务电话" message:str cancelTitle:@"取消" sureTitle:@"拨打" click:^(NSInteger index) {
                if (index==1) {
                    NSString *tel = @"tel:";
                    NSString *telUrl = [NSString stringWithFormat:@"%@%@",tel,phone];
                    NSURL *url = [[NSURL alloc] initWithString:telUrl];
                    [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:^(BOOL success) {
                        
                    }];
                }
            }];
        }else{
            NSString *tel = @"tel:";
            NSString *telUrl = [NSString stringWithFormat:@"%@%@",tel,phone];
            NSURL *url = [[NSURL alloc] initWithString:telUrl];
            [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:^(BOOL success) {
                
            }];
        }
        
        return YES;
    }else
    {
        [TGProgressHUD showHUDTip:(@"暂无联系方式")];
    }
    return NO;
}

+ (void)getEnabledDepartmentArrayWithComplemention:(ComplentValueBlock)complemention {
    [TGProgressHUD showHUD:nil];
    [EventStatisticsAPIRequest GETAllDepartmentWithsuccess:^(TGResponseItem *responseItem) {
        if (responseItem.success) {
            NSMutableArray *dataSource = [NSMutableArray array];
            NSArray *list = responseItem.data;
            
            //给第一列默认添加一个全部
            NSMutableArray *resultListArray = [NSMutableArray arrayWithArray:list];
            [resultListArray insertObject:@{@"deptName": @"全部", @"deptId": @""} atIndex:0];
            
            for (NSDictionary *tmp in resultListArray) {
                // 创建第一级数据
                LDPickerItem *item1 = [[LDPickerItem alloc]init];
                item1.name = tmp[@"deptName"];
                item1.obj = tmp[@"deptId"];
                NSArray *arr = tmp[@"children"];
                if (![arr isKindOfClass:[NSNull class]] && !EmptyCheck(tmp[@"deptId"])) {
                    // 配置第二级数据
                    //给第二列默认添加一个全部
                    NSMutableArray *resultArray = [NSMutableArray arrayWithArray:arr];
                    [resultArray insertObject:@{@"deptName": @"全部县区", @"deptId": @""} atIndex:0];
                    
                    [item1 loadData:resultArray.count config:^(LDPickerItem *item, NSInteger index) {
                        NSDictionary *tmp2 = resultArray[index];
                        item.name = tmp2[@"deptName"];
                        item.obj = tmp2[@"deptId"];

                    }];
                } else {
                    // 配置第二级数据
                    [item1 loadData:1 config:^(LDPickerItem *item, NSInteger index) {
                        item.name = @"-";
                        item.obj = @"";

                    }];
                }

                [dataSource addObject:item1];
            }

            if (complemention) {
                complemention(dataSource);
            }
        }
    } fail:^(NSError *error) {
        [TGProgressHUD dismissMPHUD];
    }];
    
}

+(void)getWarehouseArrayWithComplemention:(ComplentValueBlock)complemention
{
    [TGProgressHUD showHUD:nil];
//    [TGCustomerMangeAPIRequest GETGetEnabledDepartmentTreeSuccess:^(TGResponseItem *responseItem) {
//        [TGProgressHUD dismissMPHUD];
//        if (responseItem.success) {
//
//            NSMutableArray *dataSource = [NSMutableArray array];
//            NSArray *list = responseItem.data;
//            for (NSDictionary *tmp in list) {
//                // 创建第一级数据
//                LDPickerItem *item1 = [[LDPickerItem alloc]init];
//                item1.name = tmp[@"name"];
//                item1.obj = tmp[@"id"];
//                item1.type = [NSString stringWithFormat:@"%@",tmp[@"type"]];
//                item1.orgId = [NSString stringWithFormat:@"%@",tmp[@"orgId"]];
//                NSArray *arr = tmp[@"children"];
//                if (![arr isKindOfClass:[NSNull class]]) {
//                    // 配置第二级数据
//                    [item1 loadData:arr.count config:^(LDPickerItem *item, NSInteger index) {
//                        NSDictionary *tmp2 = arr[index];
//                        item.name = tmp2[@"name"];
//                        item.obj = tmp2[@"id"];
//                        item.type = [NSString stringWithFormat:@"%@",tmp2[@"type"]];
//                        item.orgId = [NSString stringWithFormat:@"%@",tmp2[@"orgId"]];
//                        NSArray *arr2 = tmp2[@"children"];
//                        // 配置第三极数据
//                        if (![arr2 isKindOfClass:[NSNull class]]) {
//                            [item loadData:arr2.count config:^(LDPickerItem *item, NSInteger index) {
//                                NSDictionary *tmp3 = arr2[index];
//                                item.name = tmp3[@"name"];
//                                item.obj = tmp3[@"id"];
//                                item.type = [NSString stringWithFormat:@"%@",tmp3[@"type"]];
//                                item.orgId = [NSString stringWithFormat:@"%@",tmp3[@"orgId"]];
//                            }];
//                        } else {
//                            [item loadData:1 config:^(LDPickerItem *item, NSInteger index) {
//                                item.name = @"-";
//                                item.obj = tmp2[@"id"];
//                                item.type = [NSString stringWithFormat:@"%@",tmp2[@"type"]];
//                                item.orgId = [NSString stringWithFormat:@"%@",tmp2[@"orgId"]];
//                            }];
//                        }
//
//                    }];
//                } else {
//                    // 配置第二级数据
//                    [item1 loadData:1 config:^(LDPickerItem *item, NSInteger index) {
//                        item.name = @"-";
//                        item.obj = tmp[@"id"];
//                        item.type = [NSString stringWithFormat:@"%@",tmp[@"type"]];
//                        item.orgId = [NSString stringWithFormat:@"%@",tmp[@"orgId"]];
//                        // 配置第三极数据
//                        [item loadData:1 config:^(LDPickerItem *item, NSInteger index) {
//                            item.name = @"-";
//                            item.obj = tmp[@"id"];
//                            item.type = [NSString stringWithFormat:@"%@",tmp[@"type"]];
//                            item.orgId = [NSString stringWithFormat:@"%@",tmp[@"orgId"]];
//                        }];
//
//                    }];
//                }
//
//                [dataSource addObject:item1];
//            }
//
//            if (complemention) {
//                complemention(dataSource);
//            }
//
//        }
//    } fail:^(NSError *error) {
//        [TGProgressHUD dismissMPHUD];
//    }];
}

+(void)getEnabled3LevelDeptChainWithComplemention:(ComplentValueBlock)complemention
{
    [TGProgressHUD showHUD:nil];
//    [TGCustomerMangeAPIRequest GETEnabled3LevelDeptChain:^(TGResponseItem *responseItem) {
//        [TGProgressHUD dismissMPHUD];
//        if (responseItem.success) {
//
//            NSMutableArray *dataSource = [NSMutableArray array];
//            NSArray *list = responseItem.data;
//            for (NSDictionary *tmp in list) {
//                // 创建第一级数据
//                LDPickerItem *item1 = [[LDPickerItem alloc]init];
//                item1.name = tmp[@"name"];
//                item1.obj = tmp[@"id"];
//                item1.type = [NSString stringWithFormat:@"%@",tmp[@"type"]];
//                NSArray *arr = tmp[@"children"];
//                if (![arr isKindOfClass:[NSNull class]]) {
//                    // 配置第二级数据
//                    [item1 loadData:arr.count config:^(LDPickerItem *item, NSInteger index) {
//                        NSDictionary *tmp2 = arr[index];
//                        item.name = tmp2[@"name"];
//                        item.obj = tmp2[@"id"];
//                        item.type = [NSString stringWithFormat:@"%@",tmp2[@"type"]];
//                        NSArray *arr2 = tmp2[@"children"];
//                        // 配置第三极数据
//                        if (![arr2 isKindOfClass:[NSNull class]]) {
//                            [item loadData:arr2.count config:^(LDPickerItem *item, NSInteger index) {
//                                NSDictionary *tmp3 = arr2[index];
//                                item.name = tmp3[@"name"];
//                                item.obj = tmp3[@"id"];
//                                item.type = [NSString stringWithFormat:@"%@",tmp3[@"type"]];
//                            }];
//                        } else {
//                            [item loadData:1 config:^(LDPickerItem *item, NSInteger index) {
//                                item.name = @"-";
//                                item.obj = tmp2[@"id"];
//                                item.type = [NSString stringWithFormat:@"%@",tmp2[@"type"]];
//                            }];
//                        }
//
//                    }];
//                } else {
//                    // 配置第二级数据
//                    [item1 loadData:1 config:^(LDPickerItem *item, NSInteger index) {
//                        item.name = @"-";
//                        item.obj = tmp[@"id"];
//                        item.type = [NSString stringWithFormat:@"%@",tmp[@"type"]];
//                        // 配置第三极数据
//                        [item loadData:1 config:^(LDPickerItem *item, NSInteger index) {
//                            item.name = @"-";
//                            item.obj = tmp[@"id"];
//                            item.type = [NSString stringWithFormat:@"%@",tmp[@"type"]];
//                        }];
//
//                    }];
//                }
//
//                [dataSource addObject:item1];
//            }
//
//            if (complemention) {
//                complemention(dataSource);
//            }
//
//        }
//    } fail:^(NSError *error) {
//        [TGProgressHUD dismissMPHUD];
//    }];
}
///施工场景
+ (void)getQueryTreeOrdinaryByCodeWithComplemention:(ComplentValueBlock)complemention {
    [TGProgressHUD showHUD:nil];
//    [TGCustomerMangeAPIRequest GETQueryTreeOrdinaryByCode:KConstructionScene success:^(TGResponseItem *responseItem) {
//        [TGProgressHUD dismissMPHUD];
//        if (responseItem.success) {
//
//            NSMutableArray *dataSource = [NSMutableArray array];
//            NSArray *list = responseItem.data;
//            for (NSDictionary *tmp in list) {
//                // 创建第一级数据
//                LDPickerItem *item1 = [[LDPickerItem alloc]init];
//                item1.name = tmp[@"name"];
//                item1.obj = tmp[@"code"];
//                NSArray *arr = tmp[@"childrenData"];
//                if (![arr isKindOfClass:[NSNull class]] || arr.count == 0) {
//                    // 配置第二级数据
//                    [item1 loadData:arr.count config:^(LDPickerItem *item, NSInteger index) {
//                        NSDictionary *tmp2 = arr[index];
//                        item.name = tmp2[@"name"];
//                        item.obj = tmp2[@"code"];
////                        NSArray *arr2 = tmp2[@"children"];
////                         配置第三极数据
////                        if (![arr2 isKindOfClass:[NSNull class]]) {
////                            [item loadData:arr2.count config:^(LDPickerItem *item, NSInteger index) {
////                                NSDictionary *tmp3 = arr2[index];
////                                item.name = tmp3[@"name"];
////                                item.obj = tmp3[@"id"];
////                            }];
////                        } else {
////                            [item loadData:1 config:^(LDPickerItem *item, NSInteger index) {
////                                item.name = @"-";
////                                item.obj = tmp2[@"id"];
////                            }];
////                        }
//
//                    }];
//                } else {
//                    // 配置第二级数据
//                    [item1 loadData:1 config:^(LDPickerItem *item, NSInteger index) {
//                        item.name = @"-";
//                        item.obj = tmp[@"code"];
//                        // 配置第三极数据
////                        [item loadData:1 config:^(LDPickerItem *item, NSInteger index) {
////                            item.name = @"-";
////                            item.obj = tmp[@"id"];
////                        }];
//
//                    }];
//                }
//
//                [dataSource addObject:item1];
//            }
//
//            if (complemention) {
//                complemention(dataSource);
//            }
//
//        }
//    } fail:^(NSError *error) {
//        [TGProgressHUD dismissMPHUD];
//    }];
}


///任务流撤回接口
+ (void)requestProcessCancleWithProcessId:(NSString *)processId complemention:(ComplentValueBlock)complemention {
    if (EmptyCheck(processId)) {
        [TGProgressHUD showHUDTip:@"processInstanceId为空"];
        return;
    }
    [TGLEEAlert alertTitle:@"确定要撤回审批吗？" message:nil cancelTitle:@"取消" sureTitle:@"确定" click:^(NSInteger index) {
        if (index==1) {
            
            [TGProgressHUD showHUD:nil];
//            [TGCustomerMangeAPIRequest POSTProcessCancleWithProcessInstanceId:processId success:^(TGResponseItem *responseItem) {
//                [TGProgressHUD dismissMPHUD];
//                if (responseItem.success) {
//
//                    if (complemention) {
//                        complemention(@"1");
//                    }
//
//                } else {
//
//                    if (complemention) {
//                        complemention(@"0");
//                    }
//                }
//            } fail:^(NSError *error) {
//                [TGProgressHUD dismissMPHUD];
//            }];
            
        }
    }];
   
}

//获取门店-仓库-库区 三级联动 调出地
+ (void)getEquipmentAllocationOutStoreWithComplemention:(ComplentValueBlock)complemention {
    [TGProgressHUD showHUD:nil];
//    [TGAssetsManagerAPIRequest GETGetStoreWarehousePartitionSuccess:^(TGResponseItem *responseItem) {
//        [TGProgressHUD dismissMPHUD];
//        if (responseItem.success) {
//
//            [self parseDataWithData:responseItem.data complemention:complemention];
//
//        }
//    } fail:^(NSError *error) {
//        [TGProgressHUD dismissMPHUD];
//    }];
}

//获取门店-仓库-库区 三级联动 调入地
+ (void)getEquipmentAllocationInStoreWithComplemention:(ComplentValueBlock)complemention {
    [TGProgressHUD showHUD:nil];
//    [TGAssetsManagerAPIRequest GETGetAllStoreWarehousePartitionSuccess:^(TGResponseItem *responseItem) {
//        [TGProgressHUD dismissMPHUD];
//        if (responseItem.success) {
//
//            [self parseDataWithData:responseItem.data complemention:complemention];
//
//        }
//    } fail:^(NSError *error) {
//        [TGProgressHUD dismissMPHUD];
//    }];
}

+ (void)parseDataWithData:(NSArray *)data complemention:(ComplentValueBlock)complemention {
    NSMutableArray *dataSource = [NSMutableArray array];
    
    for (NSDictionary *tmp in data) {
        // 创建第一级数据
        LDPickerItem *item1 = [[LDPickerItem alloc]init];
        item1.name = tmp[@"storeName"];
        item1.obj = tmp[@"storeId"];
        NSArray *arr = tmp[@"linkageWarehouseList"];
        if (![arr isKindOfClass:[NSNull class]]) {
            // 配置第二级数据
            [item1 loadData:arr.count config:^(LDPickerItem *item, NSInteger index) {
                NSDictionary *tmp2 = arr[index];
                item.name = tmp2[@"warehouseName"];
                item.obj = tmp2[@"warehouseId"];
                NSArray *arr2 = tmp2[@"linkagePartitionList"];
                // 配置第三极数据
                if (![arr2 isKindOfClass:[NSNull class]]) {
                    [item loadData:arr2.count config:^(LDPickerItem *item, NSInteger index) {
                        NSDictionary *tmp3 = arr2[index];
                        item.name = tmp3[@"partitionName"];
                        item.obj = [NSString stringWithFormat:@"%@|%@", tmp3[@"partitionId"], tmp3[@"address"]?:@"暂无地址"];
                    }];
                } else {
                    [item loadData:1 config:^(LDPickerItem *item, NSInteger index) {
                        item.name = @"-";
                        item.obj = tmp2[@"warehouseId"];
                    }];
                }
                
            }];
        } else {
            // 配置第二级数据
            [item1 loadData:1 config:^(LDPickerItem *item, NSInteger index) {
                item.name = @"-";
                item.obj = tmp[@"warehouseId"];
                // 配置第三极数据
                [item loadData:1 config:^(LDPickerItem *item, NSInteger index) {
                    item.name = @"-";
                    item.obj = tmp[@"partitionId"];
                }];
                
            }];
        }
        
        [dataSource addObject:item1];
    }
    
    if (complemention) {
        complemention(dataSource);
    }
}


// 下载网络文件
- (void)downloadUrl:(NSString *)urlStr fileName:(NSString *)fileName isShowAlert:(BOOL)isShowAlert {
    NSString *resultUrl = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
//    NSString *fileName = [resultUrl lastPathComponent]; //获取文件名称
     //文件名称
    
    NSURL *URL = [NSURL URLWithString:resultUrl];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    
    //判断是否存在
    if([self isFileExist:fileName]) {

        if (isShowAlert) {
            [TGLEEAlert alertTitle:@"提示" message:@"对账单下载成功,是否前往文件所在目录?" cancelTitle:@"取消" sureTitle:@"确定" click:^(NSInteger index) {
                if (index==1) {
                    [self openLocalFile];
                }
            }];
        } else {
            [self openLocalFile];
        }


    } else {
        MBProgressHUD *hud = [MBProgressHUD showMessage:@"处理中..." toView:self.getCurrentVC.view];
        NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:^(NSProgress *downloadProgress){
            double progress = 1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount;
            NSLog(@"--进度--%.2f----", progress);
            [TGGCD executeMainOpeation:^{
                hud.label.text = [NSString stringWithFormat:@"下载中 %.0f%%", progress*100];
            }];
            if (progress >= 1) {
                [TGGCD executeMainOpeation:^{
                    [hud hideAnimated:YES];
                }];
            }
        } destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
            NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
            NSURL *url = [documentsDirectoryURL URLByAppendingPathComponent:fileName];
            return url;
        } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
            [TGProgressHUD dismissMPHUD];
            [TGGCD executeMainOpeation:^{
                [hud hideAnimated:YES];
            }];
            if (isShowAlert) {
                [TGLEEAlert alertTitle:@"提示" message:@"对账单下载成功,是否前往文件所在目录?" cancelTitle:@"取消" sureTitle:@"确定" click:^(NSInteger index) {
                    if (index==1) {
                        [self openLocalFile];
                    }
                }];
            } else {
                [self openLocalFile];
            }
            
        }];
        [downloadTask resume];
    }
}

- (void)openLocalFile {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSURL *documentDirectory = [[fileManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] firstObject];
    NSURLComponents *components = [[NSURLComponents alloc] initWithURL:documentDirectory resolvingAgainstBaseURL:YES];
    components.scheme = @"shareddocuments";
    
    if (@available(iOS 10,*)) {
        [[UIApplication sharedApplication]openURL:components.URL options:@{} completionHandler:^(BOOL success) {
        }];
    } else {
        [[UIApplication sharedApplication] openURL:components.URL];
    }
}

//判断文件是否已经在沙盒中存在
- (BOOL) isFileExist:(NSString *)fileName
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [paths objectAtIndex:0];
    NSString *filePath = [path stringByAppendingPathComponent:fileName];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL result = [fileManager fileExistsAtPath:filePath];
    return result;
}

NSString *const KBuiltType = @"BuildingType";
NSString *const KConstructionScene = @"ConstructionScene";
NSString *const KConstructionWorkingCondition = @"ConstructionWorkingCondition";
NSString *const KCheckPosition = @"CheckPosition";
NSString *const KCompanyType = @"CompanyType";

NSString *const KNotificationWithLogInRefreshData = @"KNotificationWithLogInRefreshData";
NSString *const KNotificationWithRefresheMainteanceReportListVC = @"KNotificationWithRefresheMainteanceReportListVC";

NSString *const KNotificationWithRefresheEventCenterVC = @"KNotificationWithRefresheEventCenterVC";
NSString *const KNotificationWithRefresheEventDetailVC = @"KNotificationWithRefresheEventDetailVC";
NSString *const KNotificationWithRefresheEventCount = @"KNotificationWithRefresheEventCount";


@end
